<template>
  <view class="content">
    <!-- 背景图设置 -->
    <view>
      <text class="setting-title">首页背景图</text>
      <image
        :src="formData.background || defaultBackground"
        class="preview-image"
      />
      <uni-forms-item name="background" label="图片文件" required>
        <uni-file-picker
          file-mediatype="image"
          return-type="object"
          v-model="formData.background"
        ></uni-file-picker>
      </uni-forms-item>
    </view>

    <view class="spacer"></view>

    <!-- 商品列表设置 -->
    <view>
      <text class="setting-title">商品列表</text>
      <uni-table
        ref="table"
        :loading="loading"
        :emptyText="error.message || '没有更多数据'"
        border
        stripe
        type="selection"
        @selection-change="selectionChange"
      >
        <uni-tr>
          <uni-th
            align="center"
            sortable
            @sort-change="sortChange($event, 'goodsId')"
            >商品ID</uni-th
          >
          <uni-th
            align="center"
            filter-type="search"
            @filter-change="filterChange($event, 'title')"
            sortable
            @sort-change="sortChange($event, 'title')"
            >商品标题</uni-th
          >
          <uni-th align="center">操作</uni-th>
        </uni-tr>
        <uni-tr v-for="(item, index) in formData.goodsList" :key="index">
          <uni-td align="center">{{ item.goodsId }}</uni-td>
          <uni-td align="center">{{ item.title }}</uni-td>
          <uni-td align="center">
            <view class="uni-group">
              <button
                @click="removeGoods(index)"
                class="uni-button"
                size="mini"
                type="warn"
              >
                删除
              </button>
            </view>
          </uni-td>
        </uni-tr>
      </uni-table>
      <button
        v-if="formData.goodsList.length < maxGoodsCount"
        @click="addGoods"
      >
        添加商品
      </button>
    </view>

    <view class="button-group">
      <uni-button type="primary" @click="submit">保存设置</uni-button>
      <uni-button @click="cancel">取消</uni-button>
    </view>
  </view>
</template>

<script>
import {
  enumConverter,
  filterToWhere,
} from "../../js_sdk/validator/opendb-banner.js";

const db = uniCloud.database();
const dbCmd = db.command;

const orderByMapping = {
  ascending: "asc",
  descending: "desc",
};

export default {
  data() {
    return {
      cloudUploadUrl: uniCloud.uploadFileUrl,
      formData: {
        background: null,
        goodsList: [],
      },
      defaultBackground: "your_default_background_image_url", // 替换为默认背景图的 URL
      maxGoodsCount: 10,
      originalFormData: {},
      loading: false,
      error: {},
      selectedIndexs: [],
      orderby: "",
      orderByFieldName: "",
      _filter: {},
    };
  },
  async mounted() {
    const res = await uniCloud.callFunction({
      name: "ad-home-setting-get",
    });
    if (res.result) {
      this.formData = res.result;
      this.originalFormData = { ...res.result };
    }
  },
  methods: {
    addGoods() {
      if (this.formData.goodsList.length < this.maxGoodsCount) {
        this.formData.goodsList.push({
          id: Date.now(),
          goodsId: "",
          title: "新商品",
        });
      }
    },
    removeGoods(index) {
      this.formData.goodsList.splice(index, 1);
    },
    async submit() {
      uni.showLoading({
        mask: true,
      });
      try {
        const res = await uniCloud.callFunction({
          name: "ad-home-setting-save",
          data: { formData: this.formData },
        });
        if (res.result && res.result.success) {
          uni.showToast({ title: "保存成功" });
          this.originalFormData = { ...this.formData };
        } else {
          uni.showModal({
            content: res.result.message || "保存失败，请稍后重试",
            showCancel: false,
          });
        }
      } catch (err) {
        uni.showModal({
          content: err.message || "请求服务失败",
          showCancel: false,
        });
      } finally {
        uni.hideLoading();
      }
    },
    cancel() {
      this.formData = { ...this.originalFormData };
    },
    selectionChange(e) {
      this.selectedIndexs = e.detail.index;
    },
    sortChange(e, name) {
      this.orderByFieldName = name;
      if (e.order) {
        this.orderby = name + " " + orderByMapping[e.order];
      } else {
        this.orderby = "";
      }
      // 这里可以根据排序规则重新渲染表格
    },
    filterChange(e, name) {
      this._filter[name] = {
        type: e.filterType,
        value: e.filter,
      };
      let newWhere = filterToWhere(this._filter, db.command);
      if (Object.keys(newWhere).length) {
        // 这里可以根据过滤规则重新渲染表格
      } else {
        // 这里可以根据过滤规则重新渲染表格
      }
    },
  },
};
</script>

<style lang="scss">
.content {
  padding: 24rpx 32rpx;

  .setting-title {
    font-weight: 600;
    font-size: 28rpx;
    color: #333;
    padding-bottom: 16rpx;
    display: block;
  }

  .preview-image {
    width: 400rpx;
    height: 240rpx;
    border-radius: 8rpx;
    border: 1rpx solid #eee;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
    margin-bottom: 20rpx;
  }

  .spacer {
    height: 40rpx;
  }

  .button-group {
    display: flex;
    justify-content: space-between;
    margin-top: 48rpx;
  }

  .uni-button {
    width: auto;
    padding: 0 32rpx;
    height: 64rpx;
    border-radius: 32rpx;
    font-size: 28rpx;
  }
}
</style>
